import { getTenantOptions } from '@/pages/Tenant/Tenant/service';
import { ProCard } from '@ant-design/pro-components';
import {
  ProFormDigit,
  ProFormList,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProFormTimePicker,
} from '@ant-design/pro-form';
import { ProForm } from '@ant-design/pro-form/lib/layouts';
import { FooterToolbar } from '@ant-design/pro-layout';
import { Button, Col, Collapse, message, Row } from 'antd';
import { useModel } from 'umi';
import styles from '../index.less';
import { addChargeItem } from '../service';
import { addForm } from '../types';
import { encodeTimeItem, getTimeMin } from './utils';

const { Panel } = Collapse;

interface addProps {
  close: () => void;
}

export default (prop: addProps) => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const tenantId = currUser?.tenantId;

  const { close } = prop;

  return (
    <>
      <ProForm<addForm>
        submitter={{
          // 完全自定义整个区域
          render: (props, doms) => {
            return [
              <FooterToolbar key="addFooterBar">
                <Button key="rest" onClick={() => props.form?.resetFields()}>
                  重置
                </Button>
                ,
                <Button type="primary" key="submit" onClick={() => props.form?.submit?.()}>
                  提交
                </Button>
              </FooterToolbar>,
            ];
          },
        }}
        onFinish={async (values: addForm) => {
          const value: any = {
            comment: values.comment,
            name: values.name,
            tenantId: values.tenant || tenantId,
            rules: [
              {
                maxPrice: values?.maxPrice,
                effectStartTime:
                  values?.effectTime && getTimeMin(values?.effectTime[0].split(' ')[1]),
                effectEndTime: values?.effectTime && getTimeMin(values.effectTime[1].split(' ')[1]),
                timeItems: values?.timeItems?.map(encodeTimeItem),
                freeTime: values?.freeTime,
                type: 'small',
              },
            ],
          };
          const res = await addChargeItem(value);
          if (res) {
            if (res.code == 0) {
              message.success('添加成功');
              close();
              return true;
            }
            message.error('添加失败' + res?.message);
            return false;
          }

          return false;
        }}
        title="添加停车"
        // contextMenu="wwdawdawd"
      >
        <ProCard
          title={<div style={{ fontSize: 20, fontWeight: 700 }}>基本信息</div>}
          className={styles.card}
          style={{ borderBottomLeftRadius: 0, borderBottomRightRadius: 0 }}
          bordered={false}
        >
          <Row gutter={16}>
            <Col lg={8} md={12} sm={24}>
              <ProFormText
                label={'规则名称'}
                name="name"
                rules={[{ required: true, message: '请输入规则名称' }]}
                placeholder="自定义规则名称"
              />
            </Col>
            {tenantId == '1' && (
              <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
                <ProFormSelect
                  label={'所属企业'}
                  showSearch
                  name="tenant"
                  params={{ page: 1, pageSize: 10 }}
                  request={async (params, props) => {
                    const res: any = await getTenantOptions({
                      ...params,
                      name: props.text,
                    });
                    if (res)
                      return res.data.map((item: { id: any; name: any }, index: any) => {
                        return {
                          value: item.id,
                          label: item.name,
                        };
                      });
                  }}
                  rules={[{ required: true, message: '请选择所属企业' }]}
                  placeholder="选择所属企业（如未找到目标企业，请先创建企业）"
                />
              </Col>
            )}
          </Row>
          <Row gutter={16}>
            <Col lg={{ span: 18 }} md={{ span: 24 }} sm={24}>
              <ProFormTextArea
                label={'规则描述'}
                name="comment"
                rules={[{ required: true, message: '请输入规则描述' }]}
                placeholder="输入规则描述"
              />
            </Col>
          </Row>
        </ProCard>
        <ProCard
          style={{ borderTopLeftRadius: 0, borderTopRightRadius: 0 }}
          title={<div style={{ fontSize: 20, fontWeight: 700 }}>通道配置</div>}
          bordered={false}
        >
          <Collapse collapsible="header" defaultActiveKey={['0']} /*  onChange={onChange} */>
            <Panel header={`小型车配置`} key={'0'}>
              <Row gutter={16}>
                <Col lg={8} md={12} sm={24}>
                  <ProFormTimePicker.RangePicker
                    fieldProps={{
                      format: 'HH:mm',
                    }}
                    // tooltip={'免费！！！！'}
                    label={'收费时段'}
                    name="effectTime"
                    rules={[{ required: true, message: '请输入规则名称' }]}
                    placeholder={['请选择时间', '请选择时间']}
                  />
                </Col>
                <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
                  <ProFormDigit
                    label={'免费时长'}
                    name="freeTime"
                    placeholder="停车免费时长（单位：分钟）"
                    rules={[{ required: true, message: '请选择免费时长' }]}
                  />
                </Col>
              </Row>
              <Row gutter={16}>
                <Col lg={8} md={12} sm={24}>
                  <ProFormDigit
                    label={'单日最高限额'}
                    name="maxPrice"
                    placeholder="单日最高的收费限额（单位：元）"
                    rules={[{ required: true, message: '请输入单日最高限额' }]}
                  />
                </Col>
              </Row>
              <ProFormList
                name="timeItems"
                label={<div style={{ fontSize: 16, fontWeight: 700 }}>用户信息</div>}
                initialValue={[{}]}
                copyIconProps={{
                  tooltipText: '复制此行到末尾',
                }}
                deleteIconProps={{
                  tooltipText: '不需要这行了',
                }}
              >
                {(meta, index, action, count) => (
                  <Row gutter={16}>
                    <Col span={1}>
                      <ProForm.Item label="#">{index + 1}</ProForm.Item>
                    </Col>
                    <Col span={6}>
                      <ProFormDigit
                        name="startTime"
                        label="开始时间(第几个小时开始)"
                        rules={[{ required: true, message: '请输入开始时间' }]}
                      />
                    </Col>
                    <Col span={6}>
                      <ProFormDigit
                        name="endTime"
                        label="结束时间(至第几个小时)"
                        rules={[{ required: true, message: '请输入结束时间 ' }]}
                      />
                    </Col>
                    <Col span={6}>
                      <ProFormSelect
                        name="priceUnit"
                        label="时间类型"
                        options={[
                          { value: 60, label: '一小时制' },
                          { value: 30, label: '半小时制' },
                        ]}
                        rules={[{ required: true, message: '请输入时间类型' }]}
                      />
                    </Col>
                    <Col span={5}>
                      <ProFormDigit
                        name="pricing"
                        label="价格(元)"
                        fieldProps={{
                          addonAfter: '￥',
                        }}
                        rules={[{ required: true, message: '请输入价格' }]}
                      />
                    </Col>
                  </Row>
                )}
              </ProFormList>
            </Panel>
          </Collapse>
        </ProCard>
      </ProForm>
    </>
  );
};
